require('./PageMine.styl');
import { GetQueryString } from 'clientConfig/util/queryurlfield';
const reactMixin = require('react-mixin');
import urllist from 'clientConfig/urllist';
import { monStorage, Storage } from 'clientConfig/util/StoreData';;
const Actions = require('./actions');
const Store = require('./store');
import { Control } from 'react-keeper'
const net = require('clientConfig/util/net');
const ui = require('clientConfig/util/jsapi/ui');
const Arrow = require('images/svg/arrow.svg')
const { Dialog, Boxs, Button, Group, Icon, TextField, Toast, SelectField, Avatar, DatetimeField, CheckboxField, Tab } = SaltUI;
let HBox = Boxs.HBox;
let Box = Boxs.Box;
var lists = [];
var result = '';
var isshow = false;
var it_arr = [];
let apptype = GetQueryString("apptype");
let devtype = GetQueryString("devtype");
class Mine extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            content: [],
            show: isshow,
            value: '',
            active: 0
        };
        this.keys = ["headimg", "name", "nickname", "tel", "intuid", "sex", "birthday", "location", "corp", "email"];
        this.titles = ['头像', '姓名', '昵称', '手机号', '云途号', '性别', '生日', '地区', '所在单位', '邮箱'];
        this.handleClick = this.handleClick.bind(this);
        this.clickHead = this.clickHead.bind(this);
        this.handleExchange = this.handleExchange.bind(this);
        this.handleClickBind = this.handleClickBind.bind(this);
        //  debugger
        if (it_arr.length == 0) {
            this.content = [{ title: '姓名', content: Control.state.result.role.text.name }, { title: '单位', content: Control.state.result.role.text.corp_name }, { title: '手机号', content: Control.state.result.role.text.tel }, { title: '角色', content: Control.state.result.role.text.role }];
            it_arr = [Control.state.result.role.text.name, Control.state.result.role.text.corp_name, Control.state.result.role.text.tel, Control.state.result.role.text.role];
        } else {
            this.content = [{ title: '姓名', content: it_arr[0] }, { title: '单位', content: it_arr[1] }, { title: '手机号', content: it_arr[2] }, { title: '角色', content: it_arr[3] }];
        }
    }
    handleClick(index) {
        if (!this.state.show) return;
        (index == 1 || index == 2 || index == 8 || index == 9)
            && Control.go('/bind/modify/fillInfo/' + index + '/1');
        index == 5 && Control.go('/bind/modify/selectInfo/' + index + '/0/1');
        index == 7 && Control.go('/bind/modify/selectmultiInfo' + '/1');
        if (index == 4) {
            let modified = Storage.get('user.modified');
            if (!modified) {
                Control.go('/bind/modify/fillInfo/' + index + '/1')
            }
        }
    }
    //日期选择
    handleChange(field, value) {
        // console.log(value)
        if (!this.state.show) return;
        this.setState({
            [field]: value
        });
        let id = 6;
        lists[id].content = value.toString();
        lists[id].modify = true;
        lists[id].key = this.keys[id];
        // alert(JSON.stringify(lists[6]))
    }
    //点击头像
    clickHead() {
        let t = this;
        if (!this.state.show) return;
        dd.biz.util.uploadImage({
            multiple: false, //是否多选，默认false
            max: 1, //最多可选个数
            onSuccess: function (result) {
                t.setState({ src: result })
                let id = 0;
                lists[id].content = result[0];
                lists[id].modify = true;
                lists[id].key = t.keys[id];
            },
            onFail: function (err) {
                // alert(err) 
            }
        })
    }
    getCheckboxFieldProps(index) {
        if (result != '') {
            var name = result.ding.name;
            var email = result.ding.email;
            var tel = result.user.tel;
            var src = result.user.avatar;
        }
        if (index == 0) {
            var content_text = (<table className="">
                <tbody>
                    <tr>
                        <td className=" avatar-td">
                            <Avatar
                                src={src}
                                name={name}
                                className='t-SMT8 avatar'
                                size={35}
                            />
                        </td>
                        <td className="info-td">
                            <div className="name">钉钉账号信息</div>
                            <div className="postName">姓名：{name}</div>
                            <div className="postName">email：{email}</div>
                            <div className="postName">解绑的手机号：{tel}</div>
                        </td>
                    </tr>
                </tbody>
            </table>)
        } else {
            var content_text = (<table className="">
                <tbody>
                    <tr>
                        <td className=" avatar-td">
                            <Avatar
                                src={src}
                                name={this.content[4].content}
                                className='t-SMT8 avatar'
                                size={35}
                            />
                        </td>
                        <td className="info-td">
                            <div className="name">OA账号绑定信息</div>
                            <div className="postName">OA姓名：{this.content[4].content}</div>
                            <div className="postName">OA单位：{this.content[3].content}</div>
                            <div className="postName">解绑的钉钉号：{name}</div>
                        </td>
                    </tr>
                </tbody>
            </table>)
        }

        return {
            data: [
                {
                    checked: false,
                    text: content_text,
                    disable: false,
                    value: '1',
                    slotText: " "
                },

            ],
            readOnly: false,
            placeholder: "",
            maskCloseable: true,
            groupListFlag: true,
            onChange: function (data) {
                let n = data[0];
                if (n.value = '1' && n.checked) {
                    if (index == 0) {
                        //解绑钉钉号
                        var type = ['ding'];
                        dd.device.notification.confirm({
                            message: "当前登录钉钉号，确定要删除嘛",
                            title: "提示",
                            buttonLabels: ['取消', '确定'],
                            onSuccess: function (result) {
                                if (result.buttonIndex == 1) {
                                    let session = monStorage.get('user.session');
                                    let url = urllist.cancel_bind_ids + "?session=" + session;
                                    net.fetchUrl(url, { method: 'post', body: { type } }).then((jsondata) => {
                                        if (jsondata.errcode == 0) {
                                            // ui.close();
                                            if (!window.isBp) DingTalkPC.biz.navigation.quit({
                                                message: "quit message",//退出信息，传递给openModal或者openSlidePanel的onSuccess函数的result参数
                                                onSuccess: function (result) {
                                                    /**/
                                                },
                                                onFail: function () { }
                                            })
                                            else Control.go('/bind')
                                        } else {

                                        }
                                    })
                                }

                            },
                            onFail: function (err) { }
                        });
                    } else {
                        //解绑移动oa账号
                    }
                }
            },
            groupListArgument: {
                lineIndent: 25,
                itemIndent: 45
            },
            label: "",
            mode: 'slot',
            required: true,
            slotText: null
        };
    }
    handleExchange(obj) {
        let t = this;
        this.setState({ active: obj.active }, () => {
            if (this.state.active == 1) {
                // debugger
                ui.setNavigationRight({ text: "", control: false, show: false });
            } else {
                this.setui();
            }
        });
    }
    handleClickBind() {
        var type = [window.type];
        if (this.state.active == 0) {
            //解绑钉钉号    
            Dialog.confirm({
                content: "确定解绑当前【云途账号】",
                title: "提示",
                onConfirm: function () {
                    let session = monStorage.get('user.session');
                    let url = urllist.cancel_bind_ids + "?session=" + session;
                    net.fetchUrl(url, { method: 'post', body: { type } }).then((jsondata) => {
                        if (jsondata.errcode == 0) {
                            if (!window.isBp) {
                                if (apptype == 0 && devtype == 1) {
                                    //手机微应用
                                    // ui.close();
                                    Control.go('/bind/index')
                                } else if (apptype == 0 && devtype == 2) {
                                    //pc微应用
                                    Dialog.alert({
                                        title: '提示',
                                        content: '解绑成功，请重新登录',
                                        onConfirm() {
                                            Control.go('/bind/index')
                                        }
                                    });
                                }
                            } else {
                                Control.go('/bind/index')
                            }

                        } else {

                        }
                    })
                },
                onCancel: function (err) { }
            })
        } else {
            //解绑it账号
            Dialog.confirm({
                content: "确定解绑当前【IT账号】",
                title: "提示",
                onConfirm: function () {
                    let session = monStorage.get('user.session');
                    let id = Storage.get('user.id');
                    let url = urllist.unUserBind + "?session=" + session + "&id=" + id;

                    net.fetchUrl(url, { method: 'post', body: { id } }).then((jsondata) => {
                        if (jsondata.errcode == 0) {
                            return true;
                        } else {

                        }
                    }).then((judge) => {
                        if (judge) {
                            let url = urllist.cancel_bind_ids + "?session=" + session;
                            net.fetchUrl(url, { method: 'post', body: { type } }).then((jsondata) => {
                                if (jsondata.errcode == 0) {
                                    if (!window.isBp) {
                                        if (apptype == 0 && devtype == 1) {
                                            //手机微应用
                                            // ui.close();
                                            Control.go('/bind/index')
                                        } else if (apptype == 0 && devtype == 2) {
                                            //pc微应用
                                            Dialog.alert({
                                                title: '提示',
                                                content: '解绑成功，请重新登录',
                                                onConfirm() {
                                                    Control.go('/bind/index')
                                                }
                                            });
                                        }
                                    } else {
                                        Control.go('/bind/index')
                                    }
                                }
                            });
                        }
                    })
                },
                onCancel: function (err) { }
            })
        }
    }
    render() {
        let t = this;
        // let CheckboxFieldProps = this.getCheckboxFieldProps(this.state.active);

        return (
            <div className="mine mine-tab">
                <Tab active={this.state.active} onChange={this.handleExchange}>
                    <Tab.Item title="云途账号">
                        {/* <Icon name='user' className='icon' fill='orange' width={30} /> */}
                        {t.state.content.length > 0 && t.state.content.map((item, index) => {
                            if (index == 6) {
                                return (
                                    <HBox vAlign='center' style={{ borderBottom: '1px solid #E6E5E6' }}>
                                        <Box flex={2}>
                                            <DatetimeField
                                                columns={['年', '月', '日']}
                                                label="生日"
                                                onSelect={t.handleChange.bind(t, 'value')}
                                                value={t.state.value}
                                                placeholder="未设置"
                                                className='fs14 t-FAR'
                                            />
                                        </Box>
                                        <Box flex={0.8}>
                                            <Arrow width={8} height={16}
                                                className='t-MR15'
                                            />
                                        </Box>
                                    </HBox>)
                            } else {
                                return (
                                    <HBox vAlign='centre' className='content-list' onClick={() => { this.handleClick(index) }}>
                                        <Box flex={0.5}>{item.title}</Box>
                                        {index != 0 && <Box flex={1} className='t-FAR t-MR12 fs14 omit' style={{ color: '#7F7F7F' }}>{item.content}</Box>}
                                        {index == 0 && <Box flex={1} className='t-FAR t-MR12 fs14 ' style={{ color: '#7F7F7F' }} onClick={() => { this.clickHead() }}>
                                            <Avatar
                                                src={this.state.src}
                                                name="头像"
                                                className='t-MT2 avatar'
                                                size={35}
                                            />
                                        </Box>}
                                        {t.state.show && <Box flex={0.5} className='t-MR15'><Arrow width={8} height={16} /></Box>}
                                    </HBox>)
                            }
                        })}
                        {(window.isBp || DingTalkPC.ua.isDesktop) && (!t.state.show ? <Button className="button_edit" onClick={t.handleEdit.bind(this, 'edit')}>编辑</Button> : <Button className="button_edit" onClick={t.handleEdit.bind(this, 'complete')}>完成</Button>)}
                    </Tab.Item>
                    <Tab.Item title="IT账号">
                        {t.content.map((item, index) => {
                            return (
                                <HBox vAlign="center" className="content-list">
                                    <Box flex={3}>{item.title}</Box>
                                    <Box flex={2} className="t-FAL">{item.content}</Box>
                                </HBox>
                            );
                        })}
                    </Tab.Item>
                </Tab>
                <div className="t-FAC content-list-btn" onClick={this.handleClickBind}>解除绑定</div>
                {/* <CheckboxField ref='filedbox' {...CheckboxFieldProps} className='t-FAC check-box-field' /> */}
            </div>
        );
    }

    componentWillMount() {

    }
    handleEdit(type) {
        let { state: { show } } = this;
        show = !show;
        this.setState({ show }, () => {
            if (type == 'complete') Actions.submit(lists);
        })
    }
    setui() {
        let t = this;
        ui.setNavigationRight({ text: !t.state.show ? "编辑" : "完成", control: true, show: true }, (isSuccessed, result) => {
            if (isSuccessed) {
                isshow = !t.state.show
                t.setState({ show: isshow }, () => {
                    t.setui();
                    if (!t.state.show) {
                        Actions.submit(lists);
                    }
                });

            }
        });
    }
    componentDidMount() {

        if (lists.length == 0) {
            // console.log(Control.state)         
            result = Control.state.result;
            for (let i in this.titles) {
                let obj = {};
                obj.title = this.titles[i];
                obj.keys = this.keys[i];
                if (i == 0) {
                    obj.content = result.user[this.keys[i]] == '' ? (!result.ding[this.keys[i]] ? result.ding["avatar"] : result.ding[this.keys[i]]) : result.user[this.keys[i]];
                } else if (i == 8) {
                    obj.content = result.user[this.keys[i]] == '' ? (!result.ding[this.keys[i]] ? result.ding["corp_name"] : result.ding[this.keys[i]]) : result.user[this.keys[i]];
                } else {
                    obj.content = result.user[this.keys[i]] == '' ? (result.ding[this.keys[i]] == '' ? "未设置" : result.ding[this.keys[i]]) : result.user[this.keys[i]];
                }
                lists.push(obj);
                // alert(JSON.stringify(lists[0]))
            }
        } else {
            if (Control.state) {
                // alert(JSON.stringify(Control.state))
                let id = parseInt(Control.state.id)
                if (id.toString().length == 6)
                    id = 7;
                if (Control.state.content) {
                    lists[id].content = Control.state.content;
                    lists[id].modify = true;
                    lists[id].key = this.keys[id];
                }

            }
        }
        this.setState({ content: lists, src: lists[0].content, value: lists[6].content });
        (!window.isBp && !DingTalkPC.ua.isDesktop) && this.setui();
        var arrays = document.getElementsByClassName('t-layer');
        arrays[0].classList.add('visible1');
        // console.log(arrays[0].classList)
    }

    componentWillReceiveProps(nextProps) {
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
    }

    componentDidUpdate(prevProps, prevState) {
    }

    componentWillUnmount() {
        ui.setNavigationRight({ text: "", control: false, show: false });
    }
}

reactMixin.onClass(Mine, Reflux.connect(Store));

module.exports = Mine;
